package com.rz.htk.order.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rz.core.exception.GlobalException;
import com.rz.core.kit.RespKit;
import com.rz.core.resp.ResultResp;
import com.rz.htk.order.entity.Order;
import com.rz.htk.order.entity.OrderTrack;
import com.rz.htk.order.entity.vo.OrderTrackParam;
import com.rz.htk.order.service.IOrderService;
import com.rz.htk.order.service.IOrderTrackService;
import com.rz.htk.order.task.OrderTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("orderTrack")
public class OrderTrackController {
    private Logger log = LoggerFactory.getLogger("Track");

    @Resource private IOrderTrackService orderTrackService;
    @Resource private OrderTask orderTask;
    @Resource private IOrderService orderService;

    @PostMapping("syncOrderTrack")
    public ResultResp syncOrderTrack(@RequestBody JSONObject jsonObject){
        log.info("大荣回传轨迹数据 {}",jsonObject.toString());

        JSONArray array = jsonObject.getJSONArray("Data");
        if(array==null || array.size()==0){
            throw new GlobalException("轨迹数据不能为空");
        }
        OrderTrackParam param = new OrderTrackParam();
        List<OrderTrack> orderTracks = new ArrayList<>();
        array.forEach(obj->{
            JSONObject track = JSONObject.parseObject(obj.toString());
            String afterCode = track.getString("BLN");
            String info = track.getString("Status");
            String date = track.getString("Date");
            String statusCode = track.getString("StatusCode");
            String addr = track.getString("Station");
            orderTracks.add(new OrderTrack(date,addr,info,afterCode));
            param.setExpressCode(afterCode);
        });
        param.setTrackList(orderTracks);
        return RespKit.success(orderService.syncOrderTrack(param));
    }

    @PostMapping("queryList/{afterCode}")
    public ResultResp list(@PathVariable String afterCode){
        QueryWrapper<OrderTrack> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("after_code",afterCode);
        Page<OrderTrack> page = new Page<>(1, 100);
        IPage<OrderTrack> desktopIPage = orderTrackService.page(page, queryWrapper);
        return RespKit.success(desktopIPage);
    }

    @PostMapping("pushTrackToYouSu/{afterCode}")
    public ResultResp pushTrackToYouSu(@PathVariable String afterCode){
        orderTask.pushTrackToYouSu(afterCode);
        return RespKit.success(null);
    }

    @PostMapping("getYinSuTrack/{afterCode}")
    public ResultResp getYinSuTrack(@PathVariable String afterCode){
        orderTask.getYinsuTrack(afterCode);
        return RespKit.success(null);
    }

    @PostMapping("getYinSuTracks")
    public ResultResp getYinSuTracks(){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("prd_code","HTK_P0011");

        Page<Order> firstPage = new Page<>(1, 1);
        IPage<Order> pageList = orderService.page(firstPage, queryWrapper);
        getYsTrack(pageList.getRecords());
        long totalPages = pageList.getPages();
        if(totalPages>1){
            for(int i=1;i<=totalPages;i++){
                Page<Order> page = new Page<>(i, 1);
                IPage<Order> list = orderService.page(page, queryWrapper);
                getYsTrack(list.getRecords());
            }
        }
        return RespKit.success(null);
    }

    @PostMapping("processErrorTrack")
    @Transactional(rollbackFor = Exception.class)
    public ResultResp processErrorTrack(){
        Map<String,String> map = new HashMap<>();
        List<OrderTrack> tracks = orderTrackService.list();
        List<Integer> deleteOrderTrackIds = new ArrayList<>();
        List<OrderTrack> tracksUpdate = new ArrayList<>();
        tracks.forEach(orderTrack -> {
            String scanDate = orderTrack.getScanDate();
            if(!StringUtils.isEmpty(scanDate)){
                if(scanDate.contains("/")){
                    String newScanDate = scanDate.replaceAll("/","-");
                    orderTrack.setScanDate(newScanDate);
                    tracksUpdate.add(orderTrack);
                }
                String key = orderTrack.getScanDate()+orderTrack.getScanAddr()+orderTrack.getScanInfo()+orderTrack.getAfterCode();
                if(map.containsKey(key)){
                    deleteOrderTrackIds.add(orderTrack.getId());
                }else{
                    map.put(key,key);
                }
            }
        });
        log.info("纠正轨迹错误开始 {},{}",tracksUpdate.size(),deleteOrderTrackIds.size());
        boolean isok1 = orderTrackService.updateBatchById(tracksUpdate);
        boolean isok2 = orderTrackService.removeByIds(deleteOrderTrackIds);
        return RespKit.success(isok1 && isok2);
    }

    private void getYsTrack(List<Order> list){
        if(list!=null && list.size()>0){
            list.forEach(order->{
                if(order.getTrackSuccess().equals(0)){
                    orderTask.getYinsuTrack(order.getAfterCode());
                }
            });
        }
    }
}
